const jwt = require('jsonwebtoken')
const dotenv = require('dotenv')
const User = require('../models/User.js')

dotenv.config()

const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-123'

const auth = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '')

    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '未提供认证令牌',
        success: false
      })
    }

    const decoded = jwt.verify(token, JWT_SECRET)
    req.user = { userId: decoded.userId }

    next()
  } catch (error) {
    console.error('认证中间件错误:', error)
    res.status(401).json({
      code: 401,
      message: '认证失败',
      success: false
    })
  }
}

module.exports = auth
